/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\TodoList\QuotaFreeze\BatchForm.tsx
 * @Date: 2021-09-27 15:30:46
 * @LastEditTime: 2022-03-08 15:58:12
 */
import React from 'react'
import { http, IUdFormItem, UdModalForm, validators } from '@/lib'
import { Input, Radio, Select } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import todoApi from '@/apis/TodoList/index'
const { TextArea } = Input
const { Option } = Select

interface IProps {
  selectedRows?: any[]
  roleIds?:[]
}
interface IState {
  isValid: any
  approverList: any[]
}
export default class FreezeForm extends React.Component<IProps, IState> {
  private selectedRows = this.props.selectedRows
  private form: WrappedFormUtils
  private isLastApprover = false // 是否最后审批人
  private nextApproverFormItem: IUdFormItem = {
    id: 'approveUserIds',
    label: '下一审批人',
    rules: [validators.required],
    render: () => {
      return (
        <Select mode="multiple" showSearch={true} optionFilterProp="children">
          {this.state.approverList.map(item => (
            <Option key={item.value} value={item.value}>
              {item.title}
            </Option>
          ))}
        </Select>
      )
    },
  }
  private items: IUdFormItem[] = [
    {
      id: 'isValid',
      label: '审批状态',
      rules: [validators.required],
      render: (
        <Radio.Group onChange={e => this.setState({ isValid: e.target.value })}>
          <Radio value={0}>审批通过</Radio>
          <Radio value={1}>不通过</Radio>
        </Radio.Group>
      ),
    },
    {
      id: 'comment',
      label: '审批意见',
      rules: [validators.max(100), validators.noSpecialSymbol],
      render: <TextArea placeholder="请填写审批意见（限100字）" />,
    },
  ]
  constructor(props: IProps, state: IState) {
    super(props)
    this.state = {
      isValid: null,
      approverList: [],
    }
  }
  componentDidMount() {
    console.log('this.props :>> ', this.props);
    this.getNextApprover()
  }

  private getNextApprover = async () => {
    try {
      if (this.props.roleIds?.length > 0) {
        // 有下一级审批人才去选择，用于判断是否最后审批人
        const params = { ids: this.props.roleIds }
        const nextApprover = await http.post(todoApi.NextApproverList, params)
        const approverList = nextApprover.data.map(({ id: value, realName: title }) => ({ value, title }))
        this.setState({ approverList })
      } else {
        this.isLastApprover = true
      }
    } catch(err) {
      console.error(err)
    }
  }
  private onOk = () => {
    console.log('submit')
    this.form.validateFields((err, values) => {
      if (!err) {
        console.log(values)
      } else {
        console.log(err)
      }
    })
  }
  render() {
    let items =
      !this.isLastApprover && this.state.isValid === 0 ? [...this.items, this.nextApproverFormItem] : this.items
    return <UdModalForm getForm={form => (this.form = form)} items={items} getHandler={this.props['getHandler']} />
  }
}
